package com.harmonypilot.modelconfig.service;

import com.harmonypilot.modelconfig.domain.Role;
import com.harmonypilot.modelconfig.domain.User;
import com.harmonypilot.modelconfig.dto.AuthResponse;
import com.harmonypilot.modelconfig.dto.LoginRequest;
import com.harmonypilot.modelconfig.dto.RegisterRequest;
import com.harmonypilot.modelconfig.repo.UserRepository;
import com.harmonypilot.modelconfig.util.JwtUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AuthService {
    private final UserRepository userRepo;
    private final PasswordEncoder encoder;
    private final JwtUtil jwtUtil;
    // 管理员注册白名单（仅这些用户名允许注册为管理员）
    private static final java.util.Set<String> ADMIN_WHITELIST = java.util.Set.of("yaoruozi", "zhangsan");

    public AuthService(UserRepository userRepo, PasswordEncoder encoder, JwtUtil jwtUtil) {
        this.userRepo = userRepo; this.encoder = encoder; this.jwtUtil = jwtUtil;
    }

    @Transactional
    public AuthResponse register(RegisterRequest req) {
        if (userRepo.existsByUsername(req.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        User u = new User();
        u.setUsername(req.getUsername());
        u.setPasswordHash(encoder.encode(req.getPassword()));
        try {
            String want = req.getRole() == null ? "DEVELOPER" : req.getRole().toUpperCase();
            if ("ADMIN".equals(want)) {
                String uname = req.getUsername() == null ? "" : req.getUsername().toLowerCase();
                if (!ADMIN_WHITELIST.contains(uname)) {
                    throw new RuntimeException("由于权限管控，您不能注册管理员");
                }
                u.setRole(Role.ADMIN);
            } else {
                u.setRole(Role.DEVELOPER);
            }
        } catch (RuntimeException ex) {
            throw ex;
        } catch (Exception e) {
            u.setRole(Role.DEVELOPER);
        }
        userRepo.save(u);
        String token = jwtUtil.generateToken(u.getUsername(), u.getRole().name());
        return new AuthResponse(token, u.getUsername(), u.getRole().name());
    }

    @Transactional(readOnly = true)
    public AuthResponse login(LoginRequest req) {
        User u = userRepo.findByUsername(req.getUsername())
                .orElseThrow(() -> new RuntimeException("用户名或密码错误"));
        if (!encoder.matches(req.getPassword(), u.getPasswordHash())) {
            throw new RuntimeException("用户名或密码错误");
        }
        String token = jwtUtil.generateToken(u.getUsername(), u.getRole().name());
        return new AuthResponse(token, u.getUsername(), u.getRole().name());
    }
}
